package com.cqeec.gams.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqeec.gams.entity.Account;
import com.cqeec.gams.entity.FunctionalModule;
import com.cqeec.gams.mapper.AccountMapper;
import com.cqeec.gams.mapper.FunctionalModuleMapper;
import com.cqeec.gams.model.Function;

@Service
public class AccountServiceImpl implements AccountService {
	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private FunctionalModuleMapper functionalModuleMapper;

	@Override
	public Account login(String name, String password) {
		return accountMapper.findLoginAccount(name, password);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cqeec.gams.service.AccountService#checkPassword(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public boolean checkPassword(String id, String password) {
		int count = accountMapper.countByIdAndPassword(id, password);
		return count == 1 ? true : false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cqeec.gams.service.AccountService#updatePassword(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public void updatePassword(String id, String password) {
		accountMapper.updatePassword(id, password);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cqeec.gams.service.AccountService#getUserFunction(java.lang.String)
	 */
	@Override
	public List<Function> getUserFunction(String id) {
		return this.toFunciton(functionalModuleMapper.findByUserFunction(id));
	}

	/* (non-Javadoc)
	 * @see com.cqeec.gams.service.AccountService#getAllFunction()
	 */
	@Override
	public List<Function> getAllFunction() {
		return this.toFunciton(functionalModuleMapper.findAll());
	}
	
	private List<Function> toFunciton(List<FunctionalModule> functionalModules) {
		List<Function> functions = new ArrayList<>();
		// 将FunctionalModule列表数据转为Function列表数据
		String parent;
		Function function;
		// 获取功能组
		for (FunctionalModule fm : functionalModules) {
			parent = fm.getParent(); //获取功能模块的上级
			//如果没有上级表示是功能组
			if (parent == null || "".equals(parent)) {
				function = new Function(); //创建封装对象
				function.setFunctionGroupId(fm.getId()); //设置功能组的ID
				function.setFunctionGroupName(fm.getName()); //设置功能组的名称
				functions.add(function); //将功能添加到列表
			}
		}
		// 获取功能组的功能模块
		// 遍历功能组
		for (Function f : functions) {
			// 遍历所有的功能模块
			for (FunctionalModule fm : functionalModules) {
				//判断功能组的ID和功能模块的上级ID是否一致，一致则添加到功能的功能模块
				if (f.getFunctionGroupId().equals(fm.getParent())) {
					f.addFunctionalModule(fm);
				}
			}
		}
		return functions;
	}

}
